package goodenglish.infrastructure;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * @author qiuriyuchen E-mail:panpan_001@126.com
 */
public class PropUtil {
	public static final String fileName =Config.PROP_FILE;

	public static boolean getPropertyBool(String name) {
		return Boolean.parseBoolean(getProperty(name));
	}

	public static void storePropertyBool(String key, boolean value) {
		storeProperty(key, "" + value);
	}

	public static Double getPropertyDouble(String name) {
		return Double.parseDouble(getProperty(name));
	}

	public static void storePropertyDouble(String key, Double value) {
		storeProperty(key, "" + value);
	}

	public static Integer getPropertyInteger(String name) {
		return Integer.parseInt(getProperty(name));
	}

	public static void storePropertyInteger(String key, Integer value) {
		storeProperty(key, "" + value);
	}

	public static String getProperty(String name) {
		InputStream is = null;
		try {
			is = new FileInputStream(new File(fileName));
		} catch (FileNotFoundException e1) {

			e1.printStackTrace();
		}
		String str = null;
		if (is != null) {
			Properties props = new Properties();
			try {
				props.load(is);
			} catch (IOException e) {
				props = null;
			}
			if (props != null) {
				str = props.getProperty(name);
				if (str != null) {
					str = str.trim();
				}
			}

		}
		if (null != is) {
			try {
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return str;
	}

	public static void storeProperty(String key, String value) {
		OutputStream out = null;
		InputStream is = null;
		try {
			is = new FileInputStream(new File(fileName));
			Properties props = new Properties();
			props.load(is);
			out = new FileOutputStream(new File(fileName));
			if (out != null) {

				props.setProperty(key, value);
				props.store(out, "");
			}
		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			try {
				if (null != is) {
					is.close();
				}
				if (null != out) {
					out.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

}
